package com.team2.cyber_eye.background_task;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.team2.cyber_eye.ActivityHelpers.IQE;
import com.team2.cyber_eye.ActivityHelpers.Util;
import com.team2.shared.CyberException;
import com.team2.shared.CyberServer;
import com.team2.shoppingService.Server;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

public class IQEngineProcessingTask extends AsyncTask<ArrayList<Object>, Void, ArrayList<String>>{
	
	ArrayList<String> list = new ArrayList<String>();
	Bitmap pictureBitmap = null;
	String progressMessage = "";
	boolean displayError = false;
	String errorMessage = "";
	String queryID = "";
	String HashCode = "";
	
	public interface LoadingTaskFinishedListener {
		void onTaskFinished(ArrayList<String> resultList); // If you want to pass something back to the listener add a param to this method
	}
	
	// This is the progress bar you want to update while the task is in progress
	// This is the listener that will be told when this task is finished
	private final LoadingTaskFinishedListener finishedListener;
	private final Activity creator;
	
	/**
	 * A Loading task that will load some resources that are necessary for the app to start
	 * @param progressBar - the progress bar you want to update while the task is in progress
	 * @param finishedListener - the listener that will be told when this task is finished
	 */
	public IQEngineProcessingTask(LoadingTaskFinishedListener finishedListener, Activity creator)
	{
		this.finishedListener = finishedListener;
		this.creator = creator;
	}
	
	protected String CallIQE()
	{
		{
			String[] queryResult = IQE.QueryIQEngine(pictureBitmap);
			
			if (!queryResult[1].equalsIgnoreCase("Passed"))//did not pass
			{
				progressMessage = "Error in image processing";
				errorMessage = queryResult[2];
				displayError = true;
				
				return "";
			}
			else//passed
			{
				progressMessage = "Image Recognition in progress...";
				
				queryID = queryResult[0];
				//do we need to do anything with the other info??
			}
		}

		//////////////////////////////////

		{
			String[] returnResults = IQE.ResultIQEngine(queryID);
		
			if (!returnResults[1].equalsIgnoreCase("Passed"))//did not pass
			{
				progressMessage = "Error in results";
				errorMessage = returnResults[2];
				displayError = true;
				
				return "";
			}
			else//passed
			{
				progressMessage = "Analysis done...";
				
				return returnResults[0];
				//do we need to do anything with the other info??
			}
		}
		
	}
	
	protected String CallBarcode(String barcodetext)
	{
		String title = "";
		
		String timeStamp = Util.getDateString();
		String Hashable = "time_stamp" + timeStamp;
		//  Create signature  ------------------------------------------------------
	    String Secret = "barcode";
	    SecretKeySpec signingKey = new SecretKeySpec(Secret.getBytes(), "HMAC-SHA1");
	    javax.crypto.Mac HashFunc;
	    
		try {
			HashFunc = Mac.getInstance("HMAC-SHA1");
			HashFunc.init(signingKey);
		    byte[] HashBytes = HashFunc.doFinal(Hashable.getBytes());
		    HashCode = Util.HexConvert(HashBytes);
		    
		    queryID = HashCode;
		    
		    CyberServer cyberserver =  new Server();
		    
		    try {
		    	title = cyberserver.recognizeBarcode(barcodetext);
			} catch (Exception e) {
				Util.DisplayMessage(creator, "Error occurred while process barcode results");
				errorMessage = "Unable to fetch barcode information";
			}
		    
		    
		} catch (NoSuchAlgorithmException e) {
			
			Util.DisplayError(creator, "", e);
		} catch (InvalidKeyException e) {
			
			Util.DisplayError(creator, "", e);
		}
    
		return title;

	}
	
	@Override
	protected void onPostExecute(ArrayList<String> resultList) {
		super.onPostExecute(resultList);
		finishedListener.onTaskFinished(resultList); // Tell whoever was listening we have finished
	}

	@Override
	protected ArrayList<String> doInBackground(ArrayList<Object>... params) {
		
		pictureBitmap = (Bitmap) params[0].get(0);
		String iqeOrBarcode = (String) params[0].get(1);
		String barcodeText = (String) params[0].get(2);
		
		if(iqeOrBarcode.equals("iqe")){
			String statusMsg = CallIQE();
			
			list.add(statusMsg);
			list.add(queryID);
			list.add(errorMessage);
			
			return list;
		} else if(iqeOrBarcode.equals("barcode")){
			try {
				synchronized (this) {
					wait(10000);
				}
				
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}
			
			String statusMsg = CallBarcode(barcodeText);
			
			list.add(statusMsg);
			list.add(queryID);
			list.add(errorMessage);
			
			return list;
		}
		return null;
	}

}
